<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '种草区',
    navigationBarRightButton: {
      hide: true,
    },
  },
}
</route>
<template>
  <view
    class="w-full h-full bg-white overflow-hidden box-border"
    :style="{ paddingTop: safeAreaInsets?.top + 'px' }"
  >
    <view class="w-full h-full pos-relative z-1">
      <wd-navbar>
        <template #title>
          <text class="text-gray-333 font-size-36 font-500">种草区</text>
        </template>
      </wd-navbar>

      <view class="w-full h-full p-x-28 p-y-32 home-content text-gray-333 pos-relative">
        <view class="w-full hr-472 pos-absolute pos-top-0 pos-left-0 z--1">
          <image :width="'100%'" :height="'100%'" :src="headBg" />
        </view>
        <view v-for="(item, index) in grassList" :key="index" class="mg-b-32 grass-item">
          <view class="flex justify-start items-center mg-b-26">
            <view class="wr-80 hr-80 rd-40 overflow-hidden">
              <image :width="'80rpx'" :height="'80rpx'" :src="item.avatar" />
            </view>
            <view class="font-size-32 font-500 mg-l-24">{{ item.title }}</view>
          </view>
          <view
            class="w-full font-size-28 mg-b-32 overflow-x-hidden"
            @click="handleRichClick(item)"
          >
            <rich-text :nodes="item?.content"></rich-text>
          </view>
          <view class="flex flex-wrap justify-start items-center mb-2">
            <view
              class="wr-216 hr-216 mg-r-18 mg-b-24 grass-image"
              v-for="(image, img) in item.picList"
              :key="img"
            >
              <image :width="'100%'" :height="'100%'" :src="image" />
            </view>
          </view>
          <view class="flex justify-between items-center mg-b-32">
            <view class="font-size-24 text-gray-999">
              <text>{{ item.update_time }}</text>
            </view>
            <view class="flex justify-start">
              <wd-button
                plain
                icon="file-copy"
                size="small"
                custom-class="wr-164 hr-52"
                @click="toCopy(item)"
              >
                复制文字
              </wd-button>
              <!-- <wd-button
                plain
                icon="download"
                size="small"
                custom-class="wr-164 hr-52 mg-l-24"
                @click="toDownload(item)"
              >
                保存图片
              </wd-button> -->
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { getGrassPage, Grass } from '@/service/grass/grass'

defineOptions({
  name: 'Grass',
})
const headBg = ref('../../static/images/background/home-header.png')
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
const grassList: Ref<Grass[]> = ref()
onLoad(() => {
  getData()
})
const getData = () => {
  // 获取数据
  getGrassPage().then((res: any) => {
    if (res.code === 0) {
      res.data.data.map((m: any) => {
        if (m.pics.indexOf(',') > -1) {
          m.picList = m.pics.split(',')
        }
        return m
      })
      grassList.value = res.data.data
    }
  })
}
const cText: any = useCopyText()
const toCopy = (item: any) => {
  if (item.content) {
    cText.copyText(String(item.content))
  }
}
const toDownload = (item: any) => {
  if (item.content) {
    const strList = item.content.split('src="')
    const imgStr = strList[1].split('"')[0]
    uni.downloadFile({
      url: imgStr,
      success: (res: any) => {
        uni.saveFile({
          tempFilePath: res.tempFilePath,
          success: (res: any) => {
            uni.showToast({
              title: '图片已保存到相册',
              icon: 'success',
              duration: 1000,
            })
          },
        })
      },
    })
  }
}
//处理点击事件
const handleRich = (e) => {
  let imgPath = e.detail.node.attrs.src
  handlePreViewImage(imgPath)
}
const handleRichClick = (item) => {
  const str = item.content
  const regex = /<img[^>]*>/g
  const matches = str.match(regex)
  const srcRegex: any = /src="([^"]*)"/
  const imgArr: any = []
  if (matches) {
    for (let i = 0; i < matches.length; i++) {
      const imgUrl: any = matches[i].match(srcRegex)
      imgArr.push(imgUrl[1])
    }
    handlePreViewImage(imgArr)
  }
}
//预览和长按保存图片
const handlePreViewImage = (arr: any) => {
  uni.previewImage({
    urls: arr,
    longPressActions: {
      itemList: ['保存图片到相册'],
      success: function (data) {
        console.log(data.tapIndex)
        const path: any = arr[data.tapIndex]
        uni.saveImageToPhotosAlbum({
          filePath: path,
          success: function () {
            uni.showToast({
              title: '保存成功',
              duration: 2000,
            })
          },
        })
      },
      fail: function (err) {
        console.log(err.errMsg)
      },
    },
  })
}
</script>

<style scoped lang="scss">
.main-title-color {
  color: #d14328;
}
.home-container {
  position: relative;
  z-index: 1;
}
.head-bg {
  position: fixed;
  top: 0;
  left: 0;
  z-index: -1;
  width: 100vw;
  height: 472rpx;
  background-position: center;
  background-size: cover;
}
.home-content {
  height: calc(100% - var(--wot-navbar-height, 88rpx));
  overflow: auto;
}
.grass-item {
  border-bottom: 2rpx solid #f5f5f5;
}
.grass-image {
  &:nth-child(3n) {
    margin-right: 0;
  }
}
.btn-size {
  width: 164rpx;
  height: 52rpx;
  margin-left: 24rpx;
}
.time-text {
  color: #999;
}
</style>
